package com.wanaofu;

import java.util.Calendar;
import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.primefaces.component.inputtext.InputText;

public class MyPhaseListener implements PhaseListener {
	private static final long serialVersionUID = -847918143940291400L;
	
	public MyPhaseListener() {}
	
	@Override
	public void afterPhase(PhaseEvent pe) {
		System.out.println("after - " + pe.getPhaseId().toString());

		if (pe.getPhaseId() == PhaseId.PROCESS_VALIDATIONS) {
			System.out.println("=====is validation failed===" + pe.getFacesContext().isValidationFailed());
			if (pe.getFacesContext().isValidationFailed()) {
				Iterator<String> it = pe.getFacesContext().getClientIdsWithMessages() ;
				
				if (it != null) {
					while (it.hasNext()) {
						String clientID =  it.next();
//						System.out.println("=========client id with message:" + clientID);
						UIComponent target = pe.getFacesContext().getViewRoot().findComponent(clientID) ;
//						System.out.println("==========" + target.getClass());
						if (target !=null && target instanceof InputText) {
							Iterator<FacesMessage> meg = pe.getFacesContext().getMessages(clientID);
							String message = meg.next().getDetail() ;
//							System.out.println("========message:" + message );
//							System.out.println("======title attr:" + target.getAttributes().get("title") );
							target.getAttributes().put("title",message);
//							System.out.println("======title attr:" + target.getAttributes().get("title") );
						}	
					}
				}
			}
		}
			
		if (pe.getPhaseId() == PhaseId.RENDER_RESPONSE)
			System.out.println("Done with Request! " + getDatetime() + "\n");
	}

	@Override
	public void beforePhase(PhaseEvent pe) {
		if (pe.getPhaseId() == PhaseId.RESTORE_VIEW)
		      System.out.println("Processing new  Request!" + getDatetime());
		        
		System.out.println("before - " + pe.getPhaseId().toString());
		
	}

	@Override
	public PhaseId getPhaseId() {
		// TODO Auto-generated method stub
		return PhaseId.ANY_PHASE;
	}
	
	private String getDatetime(){
	    Calendar now=Calendar.getInstance();
	    String datetime =
	                 now.get(Calendar.YEAR)+"-" +
	                 (now.get(Calendar.MONTH)+1)+"-" +
	                 now.get(Calendar.DAY_OF_MONTH)+" "+
	                 now.get(Calendar.HOUR)+":"+
	                 now.get(Calendar.MINUTE)+":"+
	                 now.get(Calendar.SECOND)+
	                 now.get(Calendar.MILLISECOND);                
	    return datetime;
	 }
}
